package com.itheima.wemedia.service.impl;

import com.itheima.common.exception.LeadNewsException;
import com.itheima.common.util.AppJwtUtil;
import com.itheima.wemedia.mapper.WmUserMapper;
import com.itheima.wemedia.pojo.WmUser;
import com.itheima.wemedia.service.WmUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @version 1.0
 * @description <p>自媒体用户信息 业务实现</p>
 * @package com.itheima.wemedia.service.impl
 */
@Service
public class WmUserServiceImpl extends ServiceImpl<WmUserMapper, WmUser> implements WmUserService {
    /**
     * 通appUserId查询自媒体账号信息
     *
     * @param appUserId
     * @return
     */
    @Override
    public WmUser getByAppUserId(Integer appUserId) {
        WmUser wmUser = query().eq("ap_user_id", appUserId).one();
        return wmUser;
    }


    /**
     * 自媒体登录功能
     *
     * @param loginParam
     * @return
     */
    @Override
    public Map<String, Object> loginCheck(Map<String, String> loginParam) {
        //获取参数
        String name = loginParam.get("name");
        String password = loginParam.get("password");
        //非空判断
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
            throw new LeadNewsException("用户名或密码错误，请重新输入！");
        }
        //通过用户名查询账号
        WmUser wmUser = query().eq("name", name).one();
        //不存在报错
        if (wmUser == null) {
            throw new LeadNewsException("用户名或密码错误，请重新输入！");
        }

        //密码校验
        password += wmUser.getSalt();
        String encryptedPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!wmUser.getPassword().equals(encryptedPassword)) {
            throw new LeadNewsException("用户名或密码错误，请重新输入！");
        }
        //校验通过
        String token = AppJwtUtil.createToken(wmUser.getId().longValue());
        HashMap<String, Object> result = new HashMap<>();
        result.put("token",token);
        result.put("user",wmUser);

        return result;
    }
}
